package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author mengwei
 * @date 2019/8/12
 * @desc
 */
@Service
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    CheckGroupDao checkGroupDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckGroup> page = checkGroupDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page);
    }

    @Override
    @Transactional
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //添加数据
        checkGroupDao.add(checkGroup);
        //维护中间表数据
        if (checkGroup.getId() != null && checkitemIds != null && checkitemIds.length > 0){
            for (Integer checkitemId : checkitemIds) {
                checkGroupDao.set(checkGroup.getId(),checkitemId);
            }
        } else {
            throw new RuntimeException("检查项和检查组中间表维护失败");
        }
    }

    @Override
    public Integer[] findCheckItemIdsByCheckGroupId(Integer checkItemId) {
        return checkGroupDao.findCheckItemIdsByCheckGroupId(checkItemId);
    }

    @Override
    @Transactional
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //修改检查组数据
        checkGroupDao.edit(checkGroup);
        //先删除该检查组原来的关系
        checkGroupDao.deleteAssociation(checkGroup.getId());
        //添加新的关系
        if (checkGroup.getId() != null && checkitemIds != null && checkitemIds.length > 0){
            for (Integer checkitemId : checkitemIds) {
                checkGroupDao.set(checkGroup.getId(),checkitemId);
            }
        }
    }

    @Override
    public void delById(Integer id) {
        //判断检查组是否被套餐关联
        long count = checkGroupDao.findSetmealCountByCheckGroupId(id);
        if(count == 0){
            //先删除该检查组原来的关系
            checkGroupDao.deleteAssociation(id);
            //删除检查组
            checkGroupDao.delById(id);
        }else{
            throw new RuntimeException("检查组被套餐关联,不能删除！！！");
        }
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }
}
